package com.enhinck.dbutilweb.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author edward
 * @date 2017/11/15
 */
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
    /**
     * 1、验证码工具
     */
    @Autowired
    KaptchaConfig kaptchaConfig;

    @Autowired
    KaptchaCodeCache kaptchaCodeCache;

    /**
     * 2、生成验证码
     *
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/vcode")
    public void defaultKaptcha(@RequestParam("vCodeId") String vCodeId, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            DefaultKaptcha defaultKaptcha = kaptchaConfig.getDefaultKaptcha();
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            kaptchaCodeCache.save(vCodeId, createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}
